package cn.iocoder.yudao.module.book.controller.app.community;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.book.controller.app.community.vo.*;
import cn.iocoder.yudao.module.book.service.community.CommunityPostsService;
import cn.iocoder.yudao.module.book.service.community.PostCommentsService;
import cn.iocoder.yudao.module.book.service.community.TopicsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "APP - 社区模块")
@RestController
@RequestMapping("/api/community")
public class AppCommunityController {

    @Resource
    private CommunityPostsService communityPostsService;

    @Resource
    private PostCommentsService postCommentsService;

    @Resource
    private TopicsService topicsService;

    // ==================== 动态相关接口 ====================

    @GetMapping("/posts")
    @Operation(summary = "获取动态列表")
    public CommonResult<PageResult<CommunityPostRespVO>> getPosts(
            @Parameter(description = "分类筛选") @RequestParam(value = "category", required = false) String category,
            @Parameter(description = "页码") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @Parameter(description = "每页数量") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @Parameter(description = "用户ID筛选") @RequestParam(value = "userId", required = false) Integer userId,
            @Parameter(description = "话题ID筛选") @RequestParam(value = "topicId", required = false) Long topicId) {

        // 处理category参数，如果是"undefined"则设为null
        if ("undefined".equals(category)) {
            category = null;
        }

        Integer currentUserId = null;
        try {
            currentUserId = SecurityFrameworkUtils.getLoginUserId() != null
                    ? SecurityFrameworkUtils.getLoginUserId().intValue()
                    : null;
        } catch (Exception e) {
            // 用户未登录，currentUserId保持为null
        }

        PageResult<CommunityPostRespVO> pageResult = communityPostsService.getPostsPage(
                category, page, pageSize, currentUserId, userId, topicId);
        return success(pageResult);
    }

    @PostMapping("/posts")
    @Operation(summary = "发布动态")
    @PreAuthenticated
    public CommonResult<Map<String, Long>> createPost(@Valid @RequestBody CommunityPostCreateReqVO createReqVO) {
        Integer userId = SecurityFrameworkUtils.getLoginUserId().intValue();
        Long postId = communityPostsService.createPost(createReqVO, userId);
        Map<String, Long> map = new HashMap<>();
        map.put("post_id", postId);
        return success(map);
    }

    @GetMapping("/posts/{postId}")
    @Operation(summary = "获取动态详情")
    public CommonResult<CommunityPostRespVO> getPostDetail(@PathVariable("postId") Long postId) {
        Integer currentUserId = SecurityFrameworkUtils.getLoginUserId() != null
                ? SecurityFrameworkUtils.getLoginUserId().intValue()
                : null;

        CommunityPostRespVO post = communityPostsService.getPostDetail(postId, currentUserId);
        return success(post);
    }

    @DeleteMapping("/posts/{postId}")
    @Operation(summary = "删除动态")
    @PreAuthenticated
    public CommonResult<Void> deletePost(@PathVariable("postId") Long postId) {
        Integer userId = SecurityFrameworkUtils.getLoginUserId().intValue();
        communityPostsService.deletePost(postId, userId);
        return success(null);
    }

    // ==================== 点赞相关接口 ====================

    @PostMapping("/posts/{postId}/like")
    @Operation(summary = "点赞动态")
    @PreAuthenticated
    public CommonResult<Map<String, Integer>> likePost(@PathVariable("postId") Long postId) {
        Integer userId = SecurityFrameworkUtils.getLoginUserId().intValue();
        Integer likesCount = communityPostsService.likePost(postId, userId);
        Map<String, Integer> map = new HashMap<>();
        map.put("likes_count", likesCount);
        return success(map);
    }

    @DeleteMapping("/posts/{postId}/like")
    @Operation(summary = "取消点赞动态")
    @PreAuthenticated
    public CommonResult<Map<String, Integer>> unlikePost(@PathVariable("postId") Long postId) {
        Integer userId = SecurityFrameworkUtils.getLoginUserId().intValue();
        Integer likesCount = communityPostsService.unlikePost(postId, userId);
        Map<String, Integer> map = new HashMap<>();
        map.put("likes_count", likesCount);
        return success(map);
    }


    // ==================== 评论相关接口 ====================

    @GetMapping("/posts/{postId}/comments")
    @Operation(summary = "获取评论列表")
    public CommonResult<PageResult<PostCommentRespVO>> getComments(
            @PathVariable("postId") Long postId,
            @Parameter(description = "页码") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @Parameter(description = "每页数量") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {

        Integer currentUserId = SecurityFrameworkUtils.getLoginUserId() != null
                ? SecurityFrameworkUtils.getLoginUserId().intValue()
                : null;

        PageResult<PostCommentRespVO> pageResult = postCommentsService.getCommentsPage(
                postId, page, pageSize, currentUserId);
        return success(pageResult);
    }

    @PostMapping("/posts/{postId}/comments")
    @Operation(summary = "发布评论")
    @PreAuthenticated
    public CommonResult<Map<String, Long>> createComment(
            @PathVariable("postId") Long postId,
            @Valid @RequestBody PostCommentCreateReqVO createReqVO) {

        Integer userId = SecurityFrameworkUtils.getLoginUserId().intValue();
        Long commentId = postCommentsService.createComment(postId, createReqVO, userId);
        Map<String, Long> map = new HashMap<>();
        map.put("comment_id", commentId);
        return success(map);
    }

    @PostMapping("/comments/{commentId}/like")
    @Operation(summary = "点赞评论")
    @PreAuthenticated
    public CommonResult<Map<String, Integer>> likeComment(@PathVariable("commentId") Long commentId) {
        Integer userId = SecurityFrameworkUtils.getLoginUserId().intValue();
        Integer likesCount = postCommentsService.likeComment(commentId, userId);
        Map<String, Integer> map = new HashMap<>();
        map.put("likes_count", likesCount);
        return success(map);
    }

    @DeleteMapping("/comments/{commentId}/like")
    @Operation(summary = "取消点赞评论")
    @PreAuthenticated
    public CommonResult<Map<String, Integer>> unlikeComment(@PathVariable("commentId") Long commentId) {
        Integer userId = SecurityFrameworkUtils.getLoginUserId().intValue();
        Integer likesCount = postCommentsService.unlikeComment(commentId, userId);
        Map<String, Integer> map = new HashMap<>();
        map.put("likes_count", likesCount);
        return success(map);
    }

    // ==================== 话题相关接口 ====================

    @GetMapping("/topics/hot")
    @Operation(summary = "获取热门话题")
    public CommonResult<List<TopicRespVO>> getHotTopics(
            @Parameter(description = "限制数量") @RequestParam(value = "limit", defaultValue = "10") Integer limit) {

        List<TopicRespVO> topics = topicsService.getHotTopics(limit);
        return success(topics);
    }

    @GetMapping("/topics/search")
    @Operation(summary = "搜索话题")
    public CommonResult<List<TopicRespVO>> searchTopics(
            @Parameter(description = "搜索关键词") @RequestParam("keyword") String keyword) {

        List<TopicRespVO> topics = topicsService.searchTopics(keyword);
        return success(topics);
    }

    // ==================== 搜索接口 ====================

    @GetMapping("/search")
    @Operation(summary = "搜索动态")
    public CommonResult<PageResult<CommunityPostRespVO>> searchPosts(
            @Parameter(description = "搜索关键词") @RequestParam("keyword") String keyword,
            @Parameter(description = "分类筛选") @RequestParam(value = "category", defaultValue = "all") String category,
            @Parameter(description = "页码") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @Parameter(description = "每页数量") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

        Integer currentUserId = SecurityFrameworkUtils.getLoginUserId() != null
                ? SecurityFrameworkUtils.getLoginUserId().intValue()
                : null;

        PageResult<CommunityPostRespVO> pageResult = communityPostsService.searchPosts(
                keyword, category.equals("all") ? null : category, page, pageSize, currentUserId);
        return success(pageResult);
    }

    // ==================== 分享接口 ====================

    @PostMapping("/posts/{postId}/share")
    @Operation(summary = "分享动态")
    @PreAuthenticated
    public CommonResult<Map<String, Integer>> sharePost(@PathVariable("postId") Long postId) {
        Integer userId = SecurityFrameworkUtils.getLoginUserId().intValue();
        Integer sharesCount = communityPostsService.sharePost(postId, userId);
        Map<String, Integer> map = new HashMap<>();
        map.put("shares_count", sharesCount);
        return success(map);
    }

    // ==================== 测试接口 ====================

    @GetMapping("/test/status")
    @Operation(summary = "测试接口状态")
    public CommonResult<Map<String, Object>> testStatus() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "ok");
        result.put("message", "社区模块接口正常");
        result.put("timestamp", System.currentTimeMillis());

        // 检查用户登录状态
        try {
            Integer currentUserId = SecurityFrameworkUtils.getLoginUserId() != null
                    ? SecurityFrameworkUtils.getLoginUserId().intValue()
                    : null;
            result.put("loginStatus", currentUserId != null ? "已登录" : "未登录");
            result.put("userId", currentUserId);
        } catch (Exception e) {
            result.put("loginStatus", "未登录");
            result.put("userId", null);
        }

        return success(result);
    }

    @GetMapping("/test/data")
    @Operation(summary = "测试数据查询")
    public CommonResult<Map<String, Object>> testData() {
        Map<String, Object> result = new HashMap<>();

        try {
            // 查询动态数量
            PageResult<CommunityPostRespVO> posts = communityPostsService.getPostsPage(
                    null, 1, 5, null, null, null);
            result.put("postsCount", posts.getTotal());
            result.put("postsData", posts.getList());

            // 查询话题数量
            List<TopicRespVO> topics = topicsService.getHotTopics(5);
            result.put("topicsCount", topics.size());
            result.put("topicsData", topics);

            result.put("status", "success");
        } catch (Exception e) {
            result.put("status", "error");
            result.put("error", e.getMessage());
        }

        return success(result);
    }

}
